package com.example.serviceconsumer.controller;

import com.example.serviceconsumer.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/consumer/rest-template/products")
public class RestTemplateDemoController {

    private final RestTemplate restTemplate;
    // 服务提供者的URL，通过服务名访问
    private final String productServiceUrl = "http://service-provider/products";

    @Autowired
    public RestTemplateDemoController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    // GET: 获取所有产品
    @GetMapping
    public ResponseEntity<List<Product>> getAllProducts() {
        System.out.println("Consumer (RestTemplate): GET /products");
        // ResponseEntity<Product[]> response = restTemplate.getForEntity(productServiceUrl, Product[].class);
        // return ResponseEntity.ok(Arrays.asList(response.getBody()));
        Product[] products = restTemplate.getForObject(productServiceUrl, Product[].class);
        //使用getForObject直接获取响应体（Product数组）。
        //若结果非空，转换为List<Product>并返回200 OK；否则返回500错误。
        if (products != null) {
            return ResponseEntity.ok(Arrays.asList(products));
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    // GET: 根据ID获取产品
    @GetMapping("/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable Long id) {
        System.out.println("Consumer (RestTemplate): GET /products/" + id);
        Product product = restTemplate.getForObject(productServiceUrl + "/" + id, Product.class);
        if (product != null) {
            return ResponseEntity.ok(product);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // POST: 创建新产品
    @PostMapping
    public ResponseEntity<Product> createProduct(@RequestBody Product newProduct) {
        System.out.println("Consumer (RestTemplate): POST /products with " + newProduct);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Product> request = new HttpEntity<>(newProduct, headers);

        Product createdProduct = restTemplate.postForObject(productServiceUrl, request, Product.class);//设置请求头为JSON类型，使用postForObject发送请求。
        // 或者使用 exchange
        // ResponseEntity<Product> response = restTemplate.exchange(productServiceUrl, HttpMethod.POST, request, Product.class);
        // return response;
        return ResponseEntity.status(HttpStatus.CREATED).body(createdProduct);
    }

    // PUT: 更新产品
    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product updatedProduct) {
        System.out.println("Consumer (RestTemplate): PUT /products/" + id + " with " + updatedProduct);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Product> request = new HttpEntity<>(updatedProduct, headers);

        // restTemplate.put(productServiceUrl + "/" + id, request); // put 方法通常返回 void
        // 如果需要返回更新后的对象，可以使用 exchange
        ResponseEntity<Product> response = restTemplate.exchange(
                productServiceUrl + "/" + id,
                HttpMethod.PUT,
                request,
                Product.class
        );
        return response; // ResponseEntity.ok(updatedProduct); // 或者根据实际返回情况
    }

    // DELETE: 删除产品
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
        System.out.println("Consumer (RestTemplate): DELETE /products/" + id);
        // restTemplate.delete(productServiceUrl + "/" + id);
        // return ResponseEntity.noContent().build();

        // 使用 exchange 获取更详细的响应信息
        ResponseEntity<Void> response = restTemplate.exchange(
                productServiceUrl + "/" + id,
                HttpMethod.DELETE,
                null,
                Void.class
        );
        return ResponseEntity.status(response.getStatusCode()).build();
    }
}